/**
 * 
 */
package mx.com.asteca.vista;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import mx.com.asteca.comun.Constantes;
import mx.com.asteca.comun.dto.MateriaDTO;
import mx.com.asteca.fachada.FachadaException;
import mx.com.asteca.fachada.MateriaFachada;
import mx.com.asteca.util.RandomString;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.primefaces.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ManagedBean(name = Constantes.BEAN_REPORTE_INSTRUCTOR)
@ViewScoped
public class ReporteInstructorControlador extends BaseController implements
		Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String modulo = Constantes.MODULO_REPORTE_INSTRUCTOR;
	private String url;
	private FacesContext context = FacesContext.getCurrentInstance();

	@ManagedProperty("#{materiaFachadaImpl}")
	private MateriaFachada materiaFachada;
	private List<MateriaDTO> listaMaterias;

	private static Logger LOGGER = LoggerFactory
			.getLogger(ReporteAlumnoControlador.class);
	private boolean mostrarPanelReporte;
	private String pdfPath = "";
	
	@PostConstruct
	public void init() {
		context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		String requestURL = request.getRequestURL().toString();
		setUrl(requestURL.substring(0, requestURL.lastIndexOf("faces")));
		mostrarPanelReporte = false;
	}

	/**
	 * 
	 * @throws FachadaException
	 */
	private void initListaMaterias() {
		if (CollectionUtils.isEmpty(listaMaterias)) {
			try {
				LOGGER.debug("BUSCANDO... ");
				if (materiaFachada != null) {
					listaMaterias = materiaFachada.getAll();
				} else {
					listaMaterias = new ArrayList<MateriaDTO>();
				}
			} catch (FachadaException e) {
				listaMaterias = new ArrayList<MateriaDTO>();
				LOGGER.error(Constantes.ERROR_OBTENIENDO_LISTA_CATALOGO);
			}
		}
	}

	public void mostrarReporte() throws JRException, IOException,
			ClassNotFoundException {
		initListaMaterias();
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
				.put("instructuresReporte", listaMaterias);
		RequestContext.getCurrentInstance().execute(
				"window.open('" + url
						+ "ReporteInstructores?name=Reporte de Instructores"
						+ "')");
	}
	
	public void previsualizarReporte(){
		initListaMaterias();
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
		.put("instructuresReporte", listaMaterias);
		
		InputStream ins =  FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/JASPER/ReporteHorasInstructor"
				+ ".jrxml");
		try {
			JasperReport report = JasperCompileManager.compileReport(ins);
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("Sct",
					 FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/JASPER/img_sct.jpg"));
			param.put("Aero",
					 FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/JASPER/img_aero.jpg"));
			JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(
					listaMaterias);
			JasperPrint print = JasperFillManager.fillReport(report, param, ds);
			//print.getPages()
			//JasperPrintManager.
			byte[] file = JasperExportManager.exportReportToPdf(print);
			JasperViewer.viewReport(print);
			//downloadFile("pdf", file, response);
		} catch (JRException e) {
			e.printStackTrace();
		}
		
		
	}
	
	public void previsualizarReporte2(){
		initListaMaterias();
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
		.put("instructuresReporte", listaMaterias);
		
		InputStream ins =  FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/JASPER/ReporteHorasInstructor"
				+ ".jrxml");
		try {
			JasperReport report = JasperCompileManager.compileReport(ins);
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("Sct",
					 FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/JASPER/img_sct.jpg"));
			param.put("Aero",
					 FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/WEB-INF/JASPER/img_aero.jpg"));
			JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(
					listaMaterias);
			JasperPrint print = JasperFillManager.fillReport(report, param, ds);			
			String realPath2 = FacesContext.getCurrentInstance().getExternalContext().getRealPath("tmp");
			String path2 =  "/"+RandomString.getRandomString()+"_Reporte_Instructor_"+".pdf";
			String path = realPath2 + path2;
			File pdfTemp = new File(path);
			byte[] file = JasperExportManager.exportReportToPdf(print);
			FileUtils.writeByteArrayToFile(pdfTemp, file);
			pdfPath = "/tmp"+ path2;
			
			mostrarPanelReporte = true;
		} catch (JRException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	@Override
	String getModulo() {
		return modulo;
	}

	public FacesContext getContext() {
		return context;
	}

	public void setContext(FacesContext context) {
		this.context = context;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public MateriaFachada getMateriaFachada() {
		return materiaFachada;
	}

	public void setMateriaFachada(MateriaFachada materiaFachada) {
		this.materiaFachada = materiaFachada;
	}

	public List<MateriaDTO> getListaMaterias() {
		return listaMaterias;
	}

	public void setListaMaterias(List<MateriaDTO> listaMaterias) {
		this.listaMaterias = listaMaterias;
	}

	/**
	 * @return the mostrarPanelReporte
	 */
	public boolean isMostrarPanelReporte() {
		return mostrarPanelReporte;
	}

	/**
	 * @param mostrarPanelReporte the mostrarPanelReporte to set
	 */
	public void setMostrarPanelReporte(boolean mostrarPanelReporte) {
		this.mostrarPanelReporte = mostrarPanelReporte;
	}

	/**
	 * @return the pdfPath
	 */
	public String getPdfPath() {
		return pdfPath;
	}

	/**
	 * @param pdfPath the pdfPath to set
	 */
	public void setPdfPath(String pdfPath) {
		this.pdfPath = pdfPath;
	}

}
